package cn.sxt.userscenter.client.interceptor;

import java.net.URLEncoder;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.sxt.common.userscenter.util.ConstantFinalUtil;
import cn.sxt.common.userscenter.util.HttpUtil;
import cn.sxt.userscenter.users.pojo.AUsers;

@Component("authInterceptor")
public class AuthInterceptor extends HandlerInterceptorAdapter{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		ConstantFinalUtil.LOGGER.info("---AuthInterceptor----preHandle------");
		/* 从session 中取用户信息 */
		HttpSession session = request.getSession();
		JSONObject usersJson = (JSONObject) session.getAttribute("users");
		if(usersJson !=null){
			return true;
		}
		/* 区别第一次访问和第二次跳转 */
		String token = request.getParameter("token");
		if(token == null){
			token = "";
		}
		try {
			/* 去用户中心验证token */
			if(!"".equalsIgnoreCase(token)){
				HttpUtil httpUtil = new HttpUtil();
				/* 拼装参数json */
				JSONObject reqJson = new JSONObject();
				reqJson.put("version", "1");
				JSONObject dataJson = new JSONObject();
				dataJson.put("token", token);
				reqJson.put("data", dataJson);
				/* 验证token的url */
				String urlStr = ConstantFinalUtil.CONFIG_JSON.getString("userscenter.verifyTokenUrl");
				Map<String, String> paramMap = new HashMap<String, String>();
				paramMap.put("json", reqJson.toJSONString());
				String resp = httpUtil.methodGet(urlStr, Collections.EMPTY_MAP, paramMap);
				ConstantFinalUtil.LOGGER.info("--验证token 返回结果:{}--",resp);
				/* code consume info */
				JSONObject resultJson = (JSONObject) JSON.parse(resp);
				if("1".equalsIgnoreCase(resultJson.getString("code"))){
					/* token合法 */
					JSONObject dataResJson = resultJson.getJSONObject("data");
					usersJson = dataResJson.getJSONObject("users");
					session.setAttribute("users", usersJson);
				}
			}
		} catch (Exception e) {
			ConstantFinalUtil.LOGGER.error("跳转用户中心报错",e);
		}
		String returnUrl = request.getRequestURL() + "";
		String queryStr = request.getQueryString();
		if(queryStr == null){
			queryStr = "";
		}
		if(!"".equalsIgnoreCase(queryStr)){
			returnUrl += "?"+queryStr;
		}
		ConstantFinalUtil.LOGGER.info("-- returnUrl:{} --",returnUrl);
		/* 客户端跳转到用户中心登录的页面 */
		String loginUrl = ConstantFinalUtil.CONFIG_JSON.getString("userscenter.loginurl") + "?returnUrl=" + URLEncoder.encode(returnUrl, "UTF-8");
		ConstantFinalUtil.LOGGER.info("-- loginUrl:{} --",loginUrl);
		response.sendRedirect(loginUrl);
		return false;
	}

}
